library(plyr)

#adply--------------------------- 
vars <- c("mpg", "hp", "wt")
scars <- as.matrix(mtcars[vars])

adply(.data = scars, .margins = 2, 
      .fun = function(x){each(max, min, mean)(x)})

adply(.data = scars, .margins = 2, 
      .fun = function(x) colwise(mean, mtcars)(x))

colwise(mean, mtcars)(mtcars)

# ----------------------------------------

bnames <- read.csv("bnames.csv", header = TRUE, stringsAsFactors = FALSE)

# 以数据框的形式返回一个数据框的行数
record_count <- function(d){
  return(data.frame(count = nrow(d)))
}

record_count(bnames)

# 返回2008年的记录数量
record_count(bnames[which(bnames$year == 2008), ])

# 返回从1880 - 2008年间的记录数量
ddply(bnames, .(year), record_count)

bn2008 <- subset(bnames, year == 2008)
bn2008_boy <- subset(bn2008, sex == "boy")
bn2008_boy$rank <- rank(-bn2008_boy$percent)
head(bn2008_boy)

head(ddply(bn2008, .(year, sex), transform,
      rank = rank(-percent, ties.method = "first")))

bntop100 <- subset(bnames, rank <= 100)
bntop100_trend <- ddply(bntop100, 
                        .(year, sex),  # 按年龄和性别分类
                        summarize,
                        trend = sum(percent)
                        )

